package com.adolph.netty.buffer;

import io.netty.buffer.*;
import io.netty.util.CharsetUtil;
import javafx.util.Builder;

import java.nio.ByteBuffer;


/**
 * 〈功能概述〉<br>
 *  ByteBuffer学习
 * @author: wangxiangjun
 * @date: 2020-10-15 17:11
 */

public class ByteBufferDemo {

    public static void main(String[] args) {


//        zeroCopy();
    }

    //nio的bytebuffer
    private static void byteBuffer() {
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        String content = "测试数据！";
        //存数据
        byteBuffer.put(content.getBytes(CharsetUtil.UTF_8));
        //必须调用重置position和limit
        byteBuffer.flip();
        //读数据
        byte[] redContent = new byte[byteBuffer.remaining()];
        byteBuffer.get(redContent);

        System.out.println(new String(redContent,CharsetUtil.UTF_8));
    }


    //多个bytebuf合并
    private static void byteBuf(){
        //堆内存缓冲区
        ByteBuf byteBuf = Unpooled.buffer(10);
        String temp1 = "你好";
        byteBuf.writeBytes(temp1.getBytes());
        //直接内存缓冲区
        ByteBuf byteBuf1 = Unpooled.directBuffer(10);
        String temp2 = "不好";
        byteBuf.writeBytes(temp2.getBytes());
        //合并byteBuf，该过程零拷贝
        //写法1
        ByteBuf byteBuf2 = Unpooled.wrappedBuffer(byteBuf, byteBuf1);
        //写法2
//        CompositeByteBuf byteBufs = Unpooled.compositeBuffer();
//        byteBufs.addComponent(true,byteBuf);
//        byteBufs.addComponent(true,byteBuf1);

        byte[] read = new byte[byteBuf2.readableBytes()];
        byteBuf2.readBytes(read);
        System.out.println(new String(read));

    }


    //零拷贝
    private static void zeroCopy(){
        String temp = "测试！";
        byte[] bytes = temp.getBytes(CharsetUtil.UTF_8);
        ByteBuf byteBuf = Unpooled.wrappedBuffer(bytes);
        byte[] bytes1 = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes1);
        System.out.println(new String(bytes1));
    }

}
